package userdao

import (
	"go-web-admin/app/user/model/entity"
	"gorm.io/gorm"
)

type UserDao struct {
	DB *gorm.DB
}

// NewUserDao 定义工厂模式的函数，相当于构造器
func NewUserDao(db *gorm.DB) *UserDao {
	return &UserDao{
		DB: db,
	}
}

// FindByUsername 根据用户查询
func (u *UserDao) FindByUsername(username string) *userentity.User {
	var user userentity.User
	result := u.DB.Where("username = ?", username).First(&user)
	if result.RowsAffected == 0 {
		return nil
	}
	return &user
}

// FindById 根据用户Id查询
func (u *UserDao) FindById(userId string) *userentity.User {
	var user userentity.User
	result := u.DB.First(&user, "id = ?", userId)
	if result.RowsAffected == 0 {
		return nil
	}
	return &user
}

// SaveUser 新增用户
func (u *UserDao) SaveUser(user *userentity.User) bool {

	result := u.DB.Create(&user)

	return result.RowsAffected > 0
}
